<?php
/**
 * create by phpstorm
 * User: 冰帝
 * Date: 2023/5/4
 * Remark: 登录接口
 * 现在的努力是为了小时候吹过的牛逼
 */

namespace app\wechat\controller;


use app\BaseController;
use app\common\model\User;
use think\cache\driver\Redis;
use think\Db;
use think\facade\Cache;
use TencentCloud\Sms\V20210111\SmsClient;
// 腾讯云短信接口对应的Request类
use TencentCloud\Sms\V20210111\Models\SendSmsRequest;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Common\Credential;
// 腾讯云短信可选配置类
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
class XcxLogin extends BaseController
{
    protected $ip;
    protected $device;
    protected $is_new=1;
    protected $user;
    protected $password="teacher123";
    public function getAccessToken()
    {
        $token_url = sprintf(config('wxxcx.token_url'), config('wx.app_id'), config('wx.app_secret'));
        $access_token=Cache::get('access_token');
        if ($access_token) {
            return $access_token;
        } else {
            //
            $result = curl_get($token_url);
            $wxResult = json_decode($result, true);
            $res = Cache::set('access_token', $wxResult['access_token'],7200);
//            $redis->expire('access_token', 7200);
            return $wxResult['access_token'];
        }
    }

    public function xcx_login()
    {
        $password = input('password');
        $token = $this->getAccessToken();
        $code = input('code');
        $wxLoginUrl = sprintf(config('wxxcx.get_phone_url'),$token);
        $this->ip = $_SERVER['REMOTE_ADDR'];
        $userAgent = $_SERVER['HTTP_USER_AGENT'] ?? '';
        // 判断是否是iOS设备（iPhone/iPad）
        $this->device=$userAgent;
        $result = doCurl($wxLoginUrl,1,json_encode(['code'=>$code]));
        $wxResult = json_decode($result, true);
        if (empty($wxResult)) {
            return show(0, '获取手机号报错,微信服务内部报错');
        } else {
            if ($wxResult['errcode'] != 0) {
                return show(0, '登录报错请重试');
            }
        }
        $phone=$wxResult['phone_info']['purePhoneNumber'];
        //判断手机号是否为新增还是登录
        $user = User::getByPhone($phone);
        if ($user) {
            $uid = $user['id'];
            $this->user=$user;
            $type = $user['type'];
        } else {
            $uid = $this->newUser($phone);
            if ($uid == false) {
                return false;
            }
            $type=1;
        }
        //生成保存的数据
        $cachedValue = $this->prepareCachedValue($uid,$type);
        //保存缓存
        $token = $this->saveToCache($cachedValue);
        if($this->is_new==2&&$this->password==$password){
            return show(4, '请求成功', ['token' => $token,'user'=>$this->user]);
        }
        $data['token']=$token;
        $data['user']=$this->user;
        return show(1,'',$data);
    }
    /**\
     * @param $openid
     * @return mixed
     * 去创建新用户
     */
    private function newUser($phone)
    {
        $abc = city($this->ip);
        \think\facade\Db::startTrans();
        try {
            $one=array_rand(User::ONE_CIKU,1);
            $two=array_rand(User::TWO_CIKU,1);
            $nickname=User::ONE_CIKU[$one]."的".User::TWO_CIKU[$two];
            $nickname_count= \think\facade\Db::name('user')
                ->where('nickname','like',$nickname."%")
                ->count();
            if ($nickname_count){
                $nickname=$nickname.$nickname_count;
            }
            //生成邀请码
            $user = \think\facade\Db::name('user')
                ->insertGetId([
                    'nickname' => $nickname,
                    'create_time' => time(),
                    'ip' => $this->ip,
                    'country' => $abc['nation'],
                    'province' => $abc['region'],
                    'city' => $abc['city'],
                    'phone' => $phone,
                ]);
            $new_user['id']=$user;
            $this->user=$new_user;
            $this->is_new=2;
            \think\facade\Db::commit();
            return $user;
        } catch (\Exception $e) {
            // 回滚事务
            \think\facade\Db::rollback();
            return false;
        }
    }

    /**\
     * @param $wxResult
     * @param $uid
     * @return mixed
     * 写入缓存的数据
     */
    private function prepareCachedValue($uid,$type)
    {
        $cachedValue['uid'] = $uid;
        $cachedValue['userType'] = $type;
        return $cachedValue;
    }

    //写入缓存
    private function saveToCache($cachedValue)
    {
        //32个字符组成一组随机字符串
        $randChars = md5(date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT));
        //用三组字符串,进行md5加密
        Cache::set($randChars,serialize($cachedValue),2592000);
        return $randChars;
    }
}